'use strict';

const Controller = require('./base');
const jwt = require('jsonwebtoken');

class UserController extends Controller {

  // 获取用户
  async getInfo() {
    try {
      const { ctx, service } = this;
      const id = ctx.query.id;
      const user = await service.user.findId(id);
      this.success(user);
    } catch (err) {
      this.fail(err);
    }
  }

  // 登陆
  async doLogin() {
    try {
      const { ctx, service } = this
      const { username, password } = ctx.request.body;
      const result = await service.user.find(username, password);
      console.log(result)
      if (result) {
        if (result.status === 1) {
          const token = jwt.sign({ username: result.username }, 'USERNAME', {
            expiresIn: '1day',
          });
          ctx.set('Access-Token', token);
          const data = {
            uid: result.user_id,
            token,
          };
          this.success(data);
        }
      }
    } catch (err) {
      this.fail(err);
    }
  }

  // 登出
  async doLogout() {
    this.success({});
  }

  // 添加
  async create() {
    const { ctx, service } = this;
    const body = ctx.request.body;
    const result = await service.user.create(body);
    this.success(result);
  }

  // 用户列表
  async list() {
    const { ctx, service } = this;
    const page = ctx.query.page;
    const pageSize = 10;
    const list = await service.user.list(page, pageSize);
    this.success(list);
  }
}

module.exports = UserController;
